package cn.itcast.fore.web.action;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.AliSMSUtil;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.service.Customer;
import cn.itcast.crm.service.CustomerService;

import com.itheima.utils.Md5Util;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Controller
@Scope("prototype")
@Namespace("/")//<package namespace extends
@ParentPackage("struts-default")
@Results({@Result(name="loginsuccess",type="redirect",location="/index.html"),
	@Result(name="loginerror",location="/signup.html"),
	@Result(name="index",type="redirect",location="/index.html"),
	@Result(name="login",location="/login.html")
})
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{

	private Customer model=new Customer();
	public Customer getModel() {
		return model;
	}
	
	@Autowired
	private CustomerService customerProxy;
	
	
	/**
	  * @Description: 验证手机号是否存在
	 */
	@Action("customerAction_validateTel")
	public String validateTel() throws Exception {
		//远程调用CRM查询手机号是否存在
		Boolean flag = customerProxy.validateTel(model.getTelephone());
		ServletActionContext.getResponse().getWriter().write(flag.toString());
		return NONE;
	}
	
	
	/**
	 * @Description: 调用短信平台发送短信
	 */
	@Action("customerAction_sendCheckcode")
	public String sendCheckcode() throws Exception {
		//随机四位数字
		String randomNumeric = RandomStringUtils.randomNumeric(4);
		System.out.println(randomNumeric);
		Map<String, Object> templateParam = new HashMap<String, Object>();
		templateParam.put("code", randomNumeric);
		//调用工具类发送短信
		Boolean flag=true;
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomNumeric);
		flag = AliSMSUtil.sendMessge(model.getTelephone(), "SMS_133155205", templateParam);
		ServletActionContext.getResponse().getWriter().write(flag.toString());
		return NONE;
	}
	
	
	
	//接收验证码
	private String checkcode;
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;	
	
	//TODO NIU RUN SHENG 
	@Autowired
	private JavaMailSenderImpl  mailSender;
	
	@Resource(name = "jmsQueueTemplate")
	private JmsTemplate jmssmsTemplate;
	
	@Resource(name = "mailTemplate")
	private JmsTemplate jmsmailTemplate;
	
	
	/* *
	 * @Description: 调用CRM完成客户注册
	 */
	@Action("customerAction_regist")
	public String regist() throws Exception {
		//验证短信验证码是否正确
		String realCheckcode = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if(StringUtils.isNotBlank(realCheckcode)){
			if(realCheckcode.equals(checkcode)){
				//使用MD5对密码进行加密
				model.setPassword(Md5Util.encode(model.getPassword()));
				//注册
				customerProxy.regist(model);
				//将Session中短信验证码清空
				ServletActionContext.getRequest().getSession().removeAttribute(model.getTelephone());
				
				
				jmssmsTemplate.send("sms_msg",new MessageCreator() {
					
					public Message createMessage(Session session) throws JMSException {
						MapMessage mapMessage = session.createMapMessage();
						mapMessage.setString("tel", model.getTelephone());
						//发送客户注册成功通知      有需要模板参数
						mapMessage.setString("templateCode", "SMS_133276260");
						Map<String, Object> templateParam=new HashMap<>();
						templateParam.put("telephone", model.getTelephone());
						mapMessage.setObject("templateParam", templateParam);
						return mapMessage;
					}
				});
				
				// TODO NIU 发送邮件注册
				//激活码
				 String activeCode  = UUID.randomUUID().toString();
				 final String content = "欢迎您注册速运快递，为了提供更好的服务，请您在24小时内激活账户!!</br>"
							+ "<a href='"+MailUtils.activeUrl+"?telephone="+model.getTelephone()+"&activeCode="+activeCode  +"'>点击激活账户</a>";
				
				
				
				//TODO NIU 注册调用MQ发送邮件
				 jmsmailTemplate.send("mail_msg",new MessageCreator() {
					
					public Message createMessage(Session session) throws JMSException {
						MapMessage mailMessage = session.createMapMessage();
						mailMessage.setString("total", "恭喜注册速运快递");
						mailMessage.setString("content", content);
						mailMessage.setString("mail", "itcast_niu@126.com");//model.getEmail()
						return (Message) mailMessage;
					
						
					}
				});
				

			//将激活码存 redis数据库中
		redisTemplate.opsForValue().set(model.getTelephone(),activeCode,24,TimeUnit.HOURS);
				return "loginsuccess";
				
				
				
			}
		}
		return "loginerror";
	}
	
	
	
	//接收url传递激活码
	private String activeCode;
	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}
	
	/**
	  * @Description: 目的：确认邮箱是客户自己（远程调用CRM修改客户表中type值改为1）
	 */
	@Action("customerAction_activeMail")
	public String activeMail() throws Exception {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		//判断用户提交参数非空判断
		if(StringUtils.isNotBlank(activeCode)||StringUtils.isNotBlank(model.getTelephone())){
			//crm查询用户激活状态
			Customer customer = customerProxy.findByTelephone(model.getTelephone());
			if(customer!=null){
				//判断激活状态
				if(customer.getType()==null){
					//判断激活码是否有效
					//获取正确激活码
					String realActiveCode = redisTemplate.opsForValue().get(model.getTelephone());
					if(StringUtils.isNotBlank(realActiveCode)){
						if(activeCode.equals(realActiveCode)){
							//调用CRM完成激活
							customerProxy.activeMail(customer.getId());
							//将redis数据库中激活码删除
							redisTemplate.delete(model.getTelephone());
							ServletActionContext.getResponse().getWriter().write("激活成功，祝您使用愉快！");
						} else {
							ServletActionContext.getResponse().getWriter().write("激活码不正确！");
						}
					} else {
						//激活码失效
						ServletActionContext.getResponse().getWriter().write("激活码失效");
					}
				} else {
					ServletActionContext.getResponse().getWriter().write("账户已经激活无需重复激活！");
				}
			} else {
				ServletActionContext.getResponse().getWriter().write("账户不存在！");
			}
		} else {
			//激活链接有误
			ServletActionContext.getResponse().getWriter().write("激活链接有误");
		}
		return NONE;
	}
	
	
	
	
	/**
	  * @Description: 远程调用CRM进行登陆
	  * @return
	  * @throws Exception
	  *	  
	 */
	@Action("customerAction_login")
	public String login() throws Exception {
		//获取正确验证码(验证码在validatecode.jsp页面中存在session中)
		String realCheckcode = (String) ServletActionContext.getRequest().getSession().getAttribute("validateCode");
		if(StringUtils.isNotBlank(realCheckcode)){
			if(realCheckcode.equals(checkcode)){
				Customer customer = customerProxy.login(model.getTelephone(), Md5Util.encode(model.getPassword()));
				if(customer!=null){
					//登陆成功，将客户信息存放session
					ServletActionContext.getRequest().getSession().setAttribute("loginCustomer", customer);
					return "index";
				}
			}
		}
		return "login";
	}
	
	
	
	
	

}
